/*
███████╗██╗   ██╗ ██████╗██╗  ██╗
██╔════╝██║   ██║██╔════╝██║ ██╔╝
█████╗  ██║   ██║██║     █████╔╝ 
██╔══╝  ██║   ██║██║     ██╔═██╗ 
██║     ╚██████╔╝╚██████╗██║  ██╗
╚═╝      ╚═════╝  ╚═════╝╚═╝  ╚═╝
*/
package Service;

import common.JavaBean.EX_User;
import dao.ReviewDao;
import common.JavaBean.Review;
import common.utils.PageInfo;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class ReviewService {
    private ReviewDao reviewDao = new ReviewDao();
    private ProductService ps=new ProductService();

    // 管理员功能
    public boolean rejectReview(int reviewId) {
        try {
            reviewDao.adminRejectReview(reviewId);
            return true;
        } catch (SQLException e) {
            throw new RuntimeException("打回评论失败", e);
        }
    }

    public List<Review> searchReviews() {
        try (ResultSet rs = reviewDao.queryReviewsAdmin(null, null, null, null, null, null, null)) {
            List<Review> list = new ArrayList<>();
            while (rs.next()) {
                Review r = new Review();
                r.setReviewId(rs.getInt("review_id"));
                r.setOrderId(rs.getInt("order_id"));
                r.setUserId(rs.getInt("user_id"));
                r.setProductId(rs.getInt("product_id"));
                r.setRating(rs.getInt("rating"));
                r.setComment(rs.getString("content"));
                r.setStatus(rs.getInt("status"));
                r.setCreatedAt(rs.getTimestamp("created_at"));
                list.add(r);
            }
            return list;
        } catch (SQLException e) {
            throw new RuntimeException("查询评论失败", e);
        }
    }

    // 用户功能
    public boolean submitReview(int userId, int orderId, int rating, String content) {
        try {
            reviewDao.userSubmitReview(userId, orderId, rating, content);
            return true;
        } catch (SQLException e) {
            throw new RuntimeException("提交评论失败", e);
        }
    }

    public List<Review> getProductReviews(int productId, Timestamp start, Timestamp end, Integer minRating) {
        try {
            List<Review> reviews;
            try (ResultSet rs = reviewDao.queryReviewsAdmin(null, null,productId,
                    null, 1, null, null)) {
                reviews = new ArrayList<>();
                while (rs.next()) {
                    Review review = new Review();
                    review.setReviewId(rs.getInt("review_id"));
                    review.setOrderId(rs.getInt("order_id"));
                    review.setUserId(rs.getInt("user_id"));
                    review.setProductId(rs.getInt("product_id"));
                    review.setRating(rs.getInt("rating"));
                    review.setComment(rs.getString("comment"));
                    review.setStatus(rs.getInt("status"));
                    review.setCreatedAt(rs.getTimestamp("created_at"));
                    reviews.add(review);
                }
            }
            return reviews;
        } catch (SQLException e) {
            throw new RuntimeException("获取商品评论失败", e);
        }
    }

    public boolean withdrawReview(int reviewId) {
        return rejectReview(reviewId);
    }

    private PaymentService paymentService = new PaymentService();

    public List<Review> searchReviewsForAdmin(String username, String productname,Integer status) {
        List<Review> reviewList = new ArrayList<>();
        Integer userId = null, productId = null;

        try {
            // --- 这就是你的“懒法子”！---
            // 如果前端传来了用户名，我们就用你现成的 PaymentService 去查它的ID
            if (username != null && !username.trim().isEmpty()) {
                // 调用你已有的 searchUsers 方法，太方便了！
                List<EX_User> users = paymentService.searchUsers(null, username, null, null, null);
                if (!users.isEmpty()) {
                    // 找到了！把ID拿出来
                    userId = users.get(0).getId();
                } else {
                    // 如果按这个名字找不到用户，那就没必要继续查了，直接返回空列表
                    return reviewList;
                }
            }

            if (productname != null && !productname.trim().isEmpty()) {
                // 调用你已有的 searchUsers 方法，太方便了！
                Integer pid = ps.getProductbyname(productname);
                if (pid!=null) {
                    // 找到了！把ID拿出来
                    productId = pid;
                } else {
                    // 如果按这个名字找不到用户，那就没必要继续查了，直接返回空列表
                    return reviewList;
                }
            }

            // --- 调用你强大的 DAO 方法！---
            // 现在，我们有了 userId (可能是null)，还有时间，可以直接喂给你的存储过程了
            ResultSet rs = reviewDao.queryReviewsAdmin(null, userId, null, null, status, null, null);

            // --- 处理结果集 ---
            // 你的DAO方法返回了ResultSet，我们在这里把它转换成 List<Review>
            while (rs.next()) {
                Review review = new Review();
                // 注意：这里的列名要和你存储过程返回的列名完全一致！
                review.setReviewId(rs.getInt("review_id"));
                review.setProductId(rs.getInt("product_id"));
                review.setUserId(rs.getInt("user_id"));
                review.setOrderId(rs.getInt("order_id"));
                review.setRating(rs.getInt("rating"));
                review.setComment(rs.getString("comment"));
                review.setCreatedAt(rs.getTimestamp("created_at"));
                review.setStatus(rs.getInt("status"));
                // 假设你的存储过程也JOIN了其他表，返回了这些信息
                review.setUsername(rs.getString("username"));
                review.setProductName(rs.getString("productName"));
                reviewList.add(review);
            }
            // 千万别忘了在DAO的调用者这边关闭连接！
            // 如果你的DBUtils有办法关闭一个ResultSet继承的Statement和Connection，就用那个
            rs.getStatement().getConnection().close();

        } catch (Exception e) {
            e.printStackTrace();
            // 在生产环境中，这里应该抛出一个自定义的业务异常
            throw new RuntimeException("后台查询评论失败", e);
        }

        return reviewList;
    }
}